<template>
  <div>
    <w-modal ref="WModal" title="修改访问API权限" :success-func="successFunc">
      <template v-sloat:default>
        <a-tree
          :tree-data="allApis"
          :checked-keys="checkedKeys"
          checkable
          :replace-fields="{ key: 'api', title: 'name' }"
          @check="checkChange"
        />
      </template>
    </w-modal>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { Admin } from '@/config/api'
import WModal, { ModalFormComType } from '@/components/global/modal/form'

@Component({
  name: 'ComAdminAuthRoleApiPop',
  components: {
    WModal
  }
})
export default class Com extends Vue {
  // 原数据
  souceData = null;
  // 所有API
  allApis = [];
  // 角色模型
  roleModel: any = null;
  // 选中的数据
  checkedKeys: Array<string> = [];

  mounted () {
    this.getPages()
  }

  // 判断API是否一致
  checkApi (spiSet: Set<string>, item: any) {
    const path = `${item.path} ${item.type}`
    return spiSet.has(path)
  }

  // 显示
  show (model: any) {
    this.roleModel = model;
    (this.$refs.WModal as ModalFormComType).show()
    this.checkedKeys = model.apis
    this.allApis = JSON.parse(JSON.stringify(this.souceData))
  }

  checkChange (checkedKeys: Array<string>) {
    this.checkedKeys = checkedKeys
  }

  async successFunc () {
    await this.$wAxios.$put(`${Admin.auth.role.update}${this.roleModel._id}`, {
      apis: this.checkedKeys
    })
    this.$emit('reload')
  }

  dealWithChildren (list: Array<any>) {
    list.forEach((item) => {
      if (item.group) {
        this.dealWithChildren(item.children)
      } else {
        item.api = `${item.path} ${item.type}`
      }
    })
  }

  /**
   * 获取所有分页数据
   */
  getPages () {
    this.$wAxios
      .$get(Admin.auth.api.all)
      .then((data) => {
        this.dealWithChildren(data)
        this.souceData = data
      })
      .catch(() => {})
  }
}
</script>

<style scoped></style>
